package com.tannm.doan.taskmanager.database;

import android.database.Cursor;

public class DataTable {
	// fields
	private DataRow dataRow = null;

	// methods
	public DataTable(DataRow dataRow) {
		this.dataRow = dataRow;
	}

	public Database getUserDb() {
		return dataRow.getUserDb();
	}

	public String getTableName() {
		return dataRow.getTableName();
	}

	public DataRow getDataRow() {
		return dataRow;
	}

	public boolean createTable() {
		if (getUserDb().tableExists(getTableName())) {
			return true;
		} else {
			return getUserDb()
					.execSQL(
							getSqlTableDefinition(getTableName(), dataRow
									.getTableDef()));
		}
	}

	public String getSqlTableDefinition(String sTableName,
			DataField[] vecTableDef) {
		String def = "CREATE TABLE " + sTableName + " (";
		for (int i = 0; i < vecTableDef.length; i++) {
			def += vecTableDef[i].getColumnDefinition();
			if (i < (vecTableDef.length - 1))
				def += ", ";
		}
		def += ")";
		return def;
	}

	public long insertValues() {
		long lRowId = getUserDb().getSQLiteDb().insert(getTableName(), null,
				dataRow.getContentValues());
		return lRowId;
	}

	public long updateValues(long lRowId) {
		String sWhere = String.format("_ID = %d", lRowId);
		long lRowsUpdated = getUserDb().getSQLiteDb().update(getTableName(),
				dataRow.getContentValues(), sWhere, null);
		return lRowsUpdated;
	}

	public long deleteDataRow(long lRowId) {
		String sWhere = String.format("_ID = %d", lRowId);
		long lRowsUpdated = getUserDb().getSQLiteDb().delete(getTableName(),
				sWhere, null);
		return lRowsUpdated;
	}

	public Cursor locateDataRow(long lRowId) {
		final String s = "select * from %s where _ID = %d";
		String sql = String.format(s, getTableName(), lRowId);
		Cursor cr = getUserDb().getSQLiteDb().rawQuery(sql, null);
		// if cursor valid, set first data row as current
		if ((cr != null) && (cr.getCount() > 0))
			cr.moveToFirst();
		return cr;
	}

	public Cursor locateAlarmDataRow(int iType, long lRefID) {
		final String s = "select * from %s where Type = %d and RefID = %d";
		String sql = String.format(s, getTableName(), iType, lRefID);
		Cursor cr = getUserDb().getSQLiteDb().rawQuery(sql, null);
		// if cursor valid, set first data row as current
		if ((cr != null) && (cr.getCount() > 0))
			cr.moveToFirst();
		return cr;
	}

	public Database.Result updateData(boolean bInsertMode, long lEditRowId) {
		Database.Result result = Database.Result.errUnknown;
		if (getUserDb().isOpened()) {
			try {
				dataRow.setValuesForDataRow();
			} catch (Exception e) {
				return Database.Result.errCantSetValuesForDataRow;
			}
			// select update mode
			if (bInsertMode) {
				// insert new data row
				long lRowId = insertValues();
				if (lRowId > 0) {
					result = Database.Result.Success;
				} else {
					result = Database.Result.errCantInsertNewData;
				}
			} else {
				// update existing data row
				long lRowsUpdated = updateValues(lEditRowId);
				if (lRowsUpdated == 1) {
					result = Database.Result.Success;
				} else {
					result = Database.Result.errCantUpdateData;
				}
			}
		} else {
			result = Database.Result.errNoDbAccess;
		}
		return result;
	}

	public Database.Result deleteData(long iRowId) {
		Database.Result result = Database.Result.errUnknown;
		if (getUserDb().isOpened()) {
			if (getUserDb().tableExists(getTableName())) {
				long lRowsDeleted = deleteDataRow(iRowId);
				if (lRowsDeleted == 1) {
					result = Database.Result.Success;
				} else {
					result = Database.Result.errCantDeleteData;
				}
			} else {
				result = Database.Result.errTableNotExists;
			}
		} else {
			result = Database.Result.errNoDbAccess;
		}
		return result;
	}

	public Database.Result getRowDataForEdit(long lRowId) {
		Database.Result result = Database.Result.errUnknown;
		// get requested data row
		Cursor cr = locateDataRow(lRowId);
		if (cr == null) {
			result = Database.Result.errCantGetData;
		} else {
			if (cr.getCount() > 0) {
				if (dataRow.getValuesFromCursor(cr)) {
					try {
						dataRow.getValuesFromDataRow();
					} catch (Exception e) {
						return Database.Result.errCantGetValuesFromDataRow;
					}
					result = Database.Result.Success;
				} else {
					result = Database.Result.errCantGetDataFromTable;
				}
				cr.close();
			} else {
				result = Database.Result.errCantFindData;
			}
		}
		return result;
	}
}
